put.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '@/server/modules/users/user.service';
  3. import { z } from '@hono/zod-openapi';
  4. import { authMiddleware } from '@/server/middleware/auth.middleware';
  5. import { ErrorSchema } from '@/server/utils/errorHandler';
  6. import { AppDataSource } from '@/server/data-source';
  7. import { AuthContext } from '@/server/types/context';
  8. import { UserSchema, UpdateUserDto } from '@/server/modules/users/user.schema';
  9. const userService = new UserService(AppDataSource);
  10. const UpdateParams = z.object({
  11. id: z.coerce.number().openapi({
  12. param: { name: 'id', in: 'path' },
  13. example: 1,
  14. description: '用户ID'
  15. })
  16. });
  17. const routeDef = createRoute({
  18. method: 'put',
  19. path: '/{id}',
  20. middleware: [authMiddleware],
  21. request: {
  22. params: UpdateParams,
  23. body: {
  24. content: {
  25. 'application/json': {
  26. schema: UpdateUserDto
  27. }
  28. }
  29. }
  30. },
  31. responses: {
  32. 200: {
  33. description: '用户更新成功',
  34. content: { 'application/json': { schema: UserSchema } }
  35. },
  36. 400: {
  37. description: '无效输入',
  38. content: { 'application/json': { schema: ErrorSchema } }
  39. },
  40. 404: {
  41. description: '用户不存在',
  42. content: { 'application/json': { schema: ErrorSchema } }
  43. },
  44. 500: {
  45. description: '服务器错误',
  46. content: { 'application/json': { schema: ErrorSchema } }
  47. }
  48. }
  49. });
  50. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  51. try {
  52. const { id } = c.req.valid('param');
  53. const data = c.req.valid('json');
  54. const user = await userService.updateUser(id, data);
  55. if (!user) {
  56. return c.json({ code: 404, message: '用户不存在' }, 404);
  57. }
  58. return c.json(user, 200);
  59. } catch (error) {
  60. return c.json({
  61. code: 500,
  62. message: error instanceof Error ? error.message : '更新用户失败'
  63. }, 500);
  64. }
  65. });
  66. export default app;